package com.example.demo.spring.spring;

import java.beans.Introspector;
import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @className: LiukaiApplicationContext
 * @copyright: Copyright (C) 2019-2028, Inc. All rights reserved.
 * @company: 中兴新云.财务云
 * @author: 刘凯
 * @date: 2024/7/3
 * @Description: com.example.demo.spring.spring
 */
public class LiukaiApplicationContext {
    private Class configClass;
    private Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();
    private Map<String, Object> singletonObjects = new ConcurrentHashMap<>();
    private List<BeanPostProcessor> beanPostProcessorList = new ArrayList<>();

    public LiukaiApplicationContext(Class configClass) {
        this.configClass = configClass;
        //扫描
        if (configClass.isAnnotationPresent(ComponentScan.class)) {
            ComponentScan componentScanAnnotation = (ComponentScan) configClass.getAnnotation(ComponentScan.class);
            String path = componentScanAnnotation.value();//扫描路径

            path = path.replace(".", "/");// com/example/demo/spring/service

            ClassLoader classLoader = LiukaiApplicationContext.class.getClassLoader();
            URL resource = classLoader.getResource(path);
            File file = new File(resource.getFile());
            if(file.isDirectory()){
                File[] files = file.listFiles();
                for (File file1 : files) {
                    String fileName = file1.getAbsolutePath();
                    if (fileName.endsWith(".class")) {
                        String className = fileName.substring(fileName.indexOf("com"), fileName.indexOf(".class"));
                        className = className.replace("\\", ".");
                        Class<?> aClass = null;
                        try {
                            aClass = classLoader.loadClass(className);
                            if (aClass.isAnnotationPresent(Component.class)) {
                                if (BeanPostProcessor.class.isAssignableFrom(aClass)) {
                                    try {
                                        BeanPostProcessor instance = (BeanPostProcessor) aClass.getConstructor().newInstance();
                                        beanPostProcessorList.add(instance);
                                    } catch (InstantiationException e) {
                                        e.printStackTrace();
                                    } catch (IllegalAccessException e) {
                                        e.printStackTrace();
                                    } catch (InvocationTargetException e) {
                                        e.printStackTrace();
                                    } catch (NoSuchMethodException e) {
                                        e.printStackTrace();
                                    }
                                }
                                Component componentAnnotation = aClass.getAnnotation(Component.class);
                                String beanName = componentAnnotation.value();
                                if(beanName.equals("")){
                                    beanName = Introspector.decapitalize(aClass.getSimpleName());
                                }
                                BeanDefinition beanDefinition = new BeanDefinition();
                                if (aClass.isAnnotationPresent(Scope.class)) {
                                    Scope scopeAnnotation = aClass.getAnnotation(Scope.class);
                                    beanDefinition.setScope(scopeAnnotation.value());

                                }else {
                                    beanDefinition.setScope("singleton");
                                }
                                beanDefinition.setType(aClass);
                                beanDefinitionMap.put(beanName, beanDefinition);

                            }
                        } catch (ClassNotFoundException e) {
                            e.printStackTrace();
                        }

                    }
                }
            }
        }
        for (String beanName : beanDefinitionMap.keySet()) {
            BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
            Object bean = createBean(beanName, beanDefinition);
            singletonObjects.put(beanName, bean);
        }
    }
    private Object createBean(String beanName, BeanDefinition beanDefinition){
        Class clazz = beanDefinition.getType();
        Object o = null;
        try {
            o = clazz.getConstructor().newInstance();
            Field[] declaredFields = clazz.getDeclaredFields();
            //依赖注入
            for (Field declaredField : declaredFields) {
                if (declaredField.isAnnotationPresent(Autowired.class)) {
                    declaredField.setAccessible(true);
                    declaredField.set(o, getBean(declaredField.getName()));
                }
            }
            //beanNameAware回调机制
            if(o instanceof BeanNameAware){
                ((BeanNameAware)o).setBeanName(beanName);
            }
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                o = beanPostProcessor.postProcessBeforeInitialization(beanName, o);

            }
            //初始化机制
            if(o instanceof InitializingBean){
                ((InitializingBean)o).afterPropertiesSet();
            }

            //BeanPostProcess 初始化 AOP
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                o = beanPostProcessor.postProcessAfterInitialization(beanName, o);

            }

        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return o;
    }
    public Object getBean(String beanName) {
        BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
        if(beanDefinition == null){
            throw new NullPointerException();
        }else {
            if (beanDefinition.getScope().equals("singleton")) {
                Object object = singletonObjects.get(beanName);
                if(object == null){
                    object = createBean(beanName, beanDefinition);
                    singletonObjects.put(beanName, object);
                }
                return object;
            }else {
                Object bean = createBean(beanName, beanDefinition);
                return bean;
            }
        }
    }
}
